package ui.forms;

import db.UserManager;
import base.User;
import com.sun.lwuit.*;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.layouts.FlowLayout;
import java.io.IOException;
import javax.microedition.midlet.MIDlet;
import stub.UserServicesSoap_Stub;
import utils.Config;

/**
 * Validates the user information against the local db and takes the user to menu screen
 * @author Meera, Shayan
 */
public class LoginForm extends Form implements ActionListener {

    private final TextField txtUsername;
    private final TextField txtPassword;
    private final Button btnLogin;
    private final Button btnSignUp;
    private final MIDlet parent;

    LoginForm(final MIDlet parent) throws IOException {
        this.parent = parent;
        this.setTitle("Login");

        this.setLayout(new BoxLayout(BoxLayout.Y_AXIS));

        this.addComponent(new Label("User name:"));
        txtUsername = new TextField();
        txtUsername.setConstraint(TextField.ANY);
        this.addComponent(txtUsername);


        this.addComponent(new Label("Password"));
        txtPassword = new TextField();
        txtPassword.setConstraint(TextField.PASSWORD);
        this.addComponent(txtPassword);

        btnLogin = new Button("Login");
        btnLogin.addActionListener(this);

        btnSignUp = new Button("SignUp");
        btnSignUp.addActionListener(this);

        Container buttons = new Container(new FlowLayout(CENTER));
        buttons.addComponent(btnLogin);
        buttons.addComponent(btnSignUp);
        this.addComponent(buttons);

        this.addCommand(new Command("Exit") {

            public void actionPerformed(ActionEvent evt) {
                parent.notifyDestroyed();
            }
        });

        //#mdebug
        if (System.getProperty("microedition.platform").equalsIgnoreCase("j2me")) {
            txtUsername.setText("shayan");
            txtPassword.setText("2");
        }
        //#enddebug
    }

    public void actionPerformed(ActionEvent evt) {
        if (evt.getSource() == btnLogin) {
            try {
                if (!validate()) {
                    return;
                }

                Context.currentUser = null;
                boolean userInfoCameFromServer = false;

                User user = UserManager.getByName(txtUsername.getText());
                if (user == null) { // not found in local, search server
                    UserServicesSoap_Stub userServices = new UserServicesSoap_Stub();
                    user = userServices.getUser(txtUsername.getText(), txtPassword.getText());
                    userInfoCameFromServer = true;
                }
                if (user != null) {
                    if (user.getPassword().equals(txtPassword.getText())) {
                        Context.currentUser = user;
                        Config.setRememberedUserId(Context.currentUser.getId());
                        if (userInfoCameFromServer)
                        UserManager.persist(user);
                        //Dialog.show("Id+Id", Config.getRememberedUserId() + Context.currentUser.getId(), "OK", "");
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                Dialog.show("Error", ex.toString(), "OK", "");
            }

            if (Context.currentUser == null) {
                Dialog.show("Login failed", "Invalid username or password", "OK", "");
            } else {
                MainMenu form = new MainMenu(parent);
                form.show();
            }

        }

        if (evt.getSource() == btnSignUp) {
            SignUpForm form = new SignUpForm(this, parent);
            form.show();
        }

    }

    private boolean validate() {
        if (txtUsername.getText().equals("")) {
            Dialog.show("Error", "Please provide a value for User Name", "OK", "");
            return false;
        }

        if (txtPassword.getText().equals("")) {
            Dialog.show("Error", "Please provide a value for Password", "OK", "");
            return false;
        }
        return true;
    }
}
